package com.example.wordcardjavaproject.service.impl;

import com.example.wordcardjavaproject.bean.entity.LoginUser;
import com.example.wordcardjavaproject.bean.entity.User;
import com.example.wordcardjavaproject.redis.RedisCache;
import com.example.wordcardjavaproject.service.LoginServer;
import com.example.wordcardjavaproject.service.UserService;
import com.example.wordcardjavaproject.utils.JwtUtil;
import javax.annotation.Resource;

import com.example.wordcardjavaproject.utils.SecurityUserIdUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServerImpl implements LoginServer {

    @Resource
    UserService userService;

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Override
    public Object login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);

        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("code",20000);
        Map<String,Object > map=new HashMap<>();
        map.put("token",jwt);
        user.setPassword(null);

        // TODO 关于用户id的处理暂且先这样
        user.setId(loginUser.getUser().getId());

        map.put("user", user);
        resultMap.put("data",map);
        return resultMap;
    }
}
